package keeto.com.vn.bms.ui.adapter;

import java.util.ArrayList;

import keeto.com.vn.bms.config.BMSCore;
import keeto.com.vn.bms.config.IBMSConfig;
import keeto.com.vn.bms.model.TechniciansModel;
import keeto.com.vn.bms.network.IBMSProtocol;
import keeto.com.vn.bms.ui.activity.CreateScheduleActivity;
import keeto.com.vn.bms.ui.activity.R;
import keeto.com.vn.bms.utils.BMSListener;
import keeto.com.vn.bms.utils.BMSSharedPreferences;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ListTechnicalAdapter extends ArrayAdapter<TechniciansModel> {
	
	private Activity context;
	private ArrayList<TechniciansModel> listTechnical;
	private EditText etNameTechnical;
	private Button ivDeleteIcon;
	private BMSSharedPreferences preferences;
	private String TAG = "ListTechnicalAdapter";
	private LinearLayout llParent;
	
	Listener listener = new Listener();
	
	public ListTechnicalAdapter(Context context, ArrayList<TechniciansModel> listTechnical) {
		super(context, 0, listTechnical);
		this.context =(Activity) context;
		this.listTechnical = listTechnical;
		preferences = new BMSSharedPreferences(context);
	}
	
	
	@Override
	public View getView(final int position, View convertView, final ViewGroup parent) {
		View view = convertView;
		if (view == null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
			view = inflater.inflate(R.layout.list_technical_adapter, parent, false);
		}
		etNameTechnical = (EditText) view.findViewById(R.id.name_technical);
		ivDeleteIcon = (Button) view.findViewById(R.id.icon_delete);
		if(preferences.getTypeKeyUser(context) == 2){// neu la ki thuat vien
			ivDeleteIcon.setVisibility(View.INVISIBLE);
			etNameTechnical.setBackgroundResource(0);
			etNameTechnical.setPadding(5, 0, 0, 0);
			etNameTechnical.setTextSize(14);
		}
		etNameTechnical.setText(listTechnical.get(position).getFullname());
		etNameTechnical.setEnabled(false);
		ivDeleteIcon.setEnabled(true);
		if (listTechnical.get(position).getStatus_id().equals("1")
				|| listTechnical.get(position).getStatus_id().equals("3")
				|| listTechnical.get(position).getStatus_id().equals("4")) {  //cac trang thai technical
			ivDeleteIcon.setBackgroundResource(R.drawable.delete_icon_doctor);
			ivDeleteIcon.setEnabled(true);
			ivDeleteIcon.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if(preferences.getTypeKeyUser(context) == 4){//new la thang Admin
						AlertDialog.Builder builder = new AlertDialog.Builder(context);
		                builder.setCancelable(true);
		                builder.setTitle(context.getResources().getString(R.string.notice));
		                builder.setMessage(context.getResources().getString(R.string.notice_delete));
		                builder.setInverseBackgroundForced(true);
		                builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
	                        @Override
	                        public void onClick(DialogInterface dialog, int which) {
	                        	String ID = listTechnical.get(position).getID();
	                            BMSCore.getInstance(context).taskDeleteTechnical(preferences.getUserAuthKey(context), ID,"", listener);
	                            dialog.dismiss();
	                        }
	                    });
		                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                        @Override
	                        public void onClick(DialogInterface dialog,int which) {
	                            dialog.dismiss();
	                        }
	                    });
		                AlertDialog alert = builder.create();
		                alert.show();
					} else {   //nguoc lai la thang Bac si
						LayoutInflater inflater = LayoutInflater.from(context);
						View view = inflater.inflate(R.layout.reason_change_dialog, null);
						final Dialog builder = new Dialog(context);
						builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
						builder.setContentView(view);
						builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
						Rect displayRectangle = new Rect();
				        Window window = context.getWindow();
				        window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
				        llParent = (LinearLayout) view.findViewById(R.id.ll);
				        llParent.setMinimumWidth((int) (displayRectangle.width()* 0.9f));
						EditText etName = (EditText) view.findViewById(R.id.name_technical);
						etName.setEnabled(false);
						etName.setText(listTechnical.get(position).getFullname());
						final EditText etWriteReason = (EditText) view.findViewById(R.id.write_reason);
						Button btIconDelete = (Button) view.findViewById(R.id.icon_delete);
						Button btSent = (Button) view.findViewById(R.id.sent);
						btIconDelete.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								builder.dismiss();
							}
						});
						btSent.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {//thay doi trang thai ki thuat vien.. va co ly do
								String reason = etWriteReason.getText().toString();
								String ID = listTechnical.get(position).getID();
								String status_id = "2";
								BMSCore.getInstance(context).taskPoseNotParticipate(status_id, ID,reason, preferences.getUserAuthKey(context), listener);
								builder.dismiss();
							}
						});
						builder.show();
					}
				}
				
			});
		} else if(listTechnical.get(position).getStatus_id().equals("2")){//duoc yeu cau thay doi
			Log.e(TAG, "duoc yeu cau thay doi");
			if(preferences.getTypeKeyUser(context) != 2){
				ivDeleteIcon.setText("!");
				ivDeleteIcon.setTextColor(context.getResources().getColor(R.color.white));
				ivDeleteIcon.setBackgroundResource(R.drawable.choxet);
			}
			ivDeleteIcon.setEnabled(true);
			if(CreateScheduleActivity.preferences.getTypeKeyUser(context) == 4){ //neu la Admin
				ivDeleteIcon.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						LayoutInflater inflater = LayoutInflater.from(context);
						View view = inflater.inflate(R.layout.reason_remove, null);
						final Dialog builder = new Dialog(context,R.style.myBackgroundStyle);
						builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
						builder.setContentView(view);
						Button btConfirm = (Button) view.findViewById(R.id.bt_remove_confirm);
						Button btCancel = (Button) view.findViewById(R.id.bt_remove_cancel);
						TextView tvName = (TextView) view.findViewById(R.id.tv_remove_name);
						TextView tvContent = (TextView) view.findViewById(R.id.tv_remove_content);
						if(!listTechnical.get(position).getReason().equals(null)){
							tvContent.setText(listTechnical.get(position).getReason());
						}
						tvName.setText(listTechnical.get(position).getFullname()+" ");
						btConfirm.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								String ID = listTechnical.get(position).getID();
								String status_id = "3";
								BMSCore.getInstance(context).taskPoseNotParticipate(status_id, ID,"", preferences.getUserAuthKey(context), listener);
								builder.dismiss();
								Intent intent = new Intent();
								intent.setAction(IBMSConfig.KEY_ACTION_ADMIN_TECHNICAL);
								context.sendBroadcast(intent);
							}
						});
						btCancel.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								String ID = listTechnical.get(position).getID();
								String status_id = "4";
								BMSCore.getInstance(context).taskPoseNotParticipate(status_id, ID,"", preferences.getUserAuthKey(context), listener);
								builder.dismiss();
								Intent intent = new Intent();
								intent.setAction(IBMSConfig.KEY_ACTION_ADMIN_TECHNICAL);
								context.sendBroadcast(intent);
							}
						});
						builder.show();
					}
				});
			} else { //cac tai khoan khac thi khong cho click
				ivDeleteIcon.setEnabled(false);
			}
		}
		
		if (CreateScheduleActivity.test == 1) {//lich mo da duoc hoan thanh hoac lich mo da duoc huy
			ivDeleteIcon.setEnabled(false);
		}
		return view;
	}
	
	public static void hideKeybroad(Context ctx)
	{
	    InputMethodManager inputManager = (InputMethodManager) ctx.getSystemService(ctx.INPUT_METHOD_SERVICE);
	    inputManager.hideSoftInputFromWindow(new View(ctx).getWindowToken(), 0);
	}
	
	class Listener extends BMSListener{
		@Override
		public void finishDeleteTechnical(final int returnCode, String resultMsg) {
			super.finishDeleteTechnical(returnCode, resultMsg);
			context.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (returnCode == IBMSProtocol.STATUS_CODE_OK){
						showMessageToast(context.getResources().getString(R.string.sussess));
//						phai dung BroadCastReceived de load lai datta khi ma da xoa
						//an ban phim
						hideKeybroad(context);
						Intent intent = new Intent();
						intent.setAction(IBMSConfig.KEY_ACTION_DELETE_TECHNICAL);
						context.sendBroadcast(intent);
					} else {
						showMessageToast(context.getResources().getString(R.string.fail));
						hideKeybroad(context);
					}
				}
			});
		}
		@Override
		public void finishPoseNotParticipate(final int returnCode, String resultMsg) {
			super.finishPoseNotParticipate(returnCode, resultMsg);
			context.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (returnCode == IBMSProtocol.STATUS_CODE_OK){
						showMessageToast(context.getResources().getString(R.string.sussess));
						Intent intent = new Intent();
						intent.setAction(IBMSConfig.KEY_ACTION_REMOVE_TECHNICAL);
						context.sendBroadcast(intent);
					} else {
						showMessageToast(context.getResources().getString(R.string.fail));
					}
				}
			});
		}
	}
	
	protected void showMessageToast(final String message) {
		context.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
			}
		});
	}

}
